
const cache = require("../cache")
const sendWechatNotify = require('./wechatNotify')
const btsHelper = require('../btsHelper')

var monitorCoins = { "xsd": "1.3.4381", "trtt": "1.3.3902" }
const asssetList = Array.from(Object.keys(monitorCoins), (val, index) => monitorCoins[val]);
var recentlyTransfer = []
const amountLimit = 1000 //大于这个数值才通知

async function handleCoinTransfer(trans) {
    var op = trans.operations[0][0]
    if (op != 14) {
        return
    }

    const operation = trans.operations[0][1]

    const issuerId = operation.issuer
    const receiverId = operation.issue_to_account
    const amount = operation.asset_to_issue.amount
    const asset_id = operation.asset_to_issue.asset_id

    if (!asssetList.includes(asset_id)) {
        return
    }
    var asset = await cache.getAssetSymbol(asset_id)
    const precision = asset.precision
    const realAmount = Math.round(amount / Math.pow(10, precision))
    if (realAmount < amountLimit) {
        console.log("amount limit, pass")
        return
    }


    const issuerName = await cache.getAccountName(issuerId)
    const receiverName = await cache.getAccountName(receiverId)
    //const asset = await cache.getAssetSymbol(asset_id)
    const assetName = asset.symbol

    var txid = btsHelper.getTxId(trans)
    if (!recentlyTransfer.includes(txid)) {
        await sendWechatNotify("发现 {0} 转账".format(assetName), " {0} 转账{1}个 {2} 到CB".format(receiverName, realAmount, assetName))

        recentlyTransfer.push(txid)
    }

    if (recentlyTransfer.length > 100) {
        recentlyTransfer = recentlyTransfer.slice(90)
    }

    console.log("【{0}】 发行【{1}】个【{2}】给 【{3}】".format(issuerName, realAmount, assetName, receiverName))
}

module.exports = handleCoinTransfer